package com.aivin;


import java.io.File;
import java.util.HashMap;
import java.util.Scanner;

public class GitTool {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder();
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectError(ProcessBuilder.Redirect.INHERIT);
        File workDir = new File("./");
        if (!workDir.exists()) {
            boolean result = workDir.mkdirs();
        }
        builder.directory(workDir);

        checkGitBaseInfo(builder);
        String choice = showScannerTips("请输入你要的操作：(" +
                "0、退出 " +
                "1、clone " +
                "2、pull ," +
                "3、添加远程分支映射 " +
                "4、合并不同仓库的代码) ");
        switch (choice) {
            case "0":
                LyLog.showLog("已退出");
                break;
            case "1":
                clonePro(builder);
                break;
            case "2":
                pullCmd(builder);
                break;
            case "3":
                setShortnameMap(builder);
                break;
            case "4":
                mergeRepo(builder);
                break;
            default:
                break;
        }
    }

    /**
     * 合并两个仓库的代码。
     * git 合并 fork 的仓库代码
     */
    public static void mergeRepo(ProcessBuilder builder) throws Exception{
        //git remote add upstream <original-repository-url>
        // 1、在你的本地仓库中添加原始仓库作为一个远程仓库映射。名字随意。这通常被称为 "upstream"。
        String cmd ="git remote add upstream https://gitee.com/hnyer/GitDemo2.git" ;
        builder.command(cmd.split(" ")).start().waitFor();
        // 2、拉取最新的更改到你的本地仓库
        builder.command("git fetch upstream".split(" ")).start().waitFor();
        // 3、将本地分支切换到 master分支，准备将远程的代码合并过来
        builder.command("git checkout master".split(" ")).start().waitFor();
        // 4、合并远程仓库的master分支 代码到本地当前分支
        builder.command("git merge upstream/master".split(" ")).start().waitFor();
    }


    public static String showScannerTips(String tips) {
        LyLog.showLog(tips);
        Scanner scanner = new Scanner(System.in);
        return scanner.next();
    }

    public static void setShortnameMap(ProcessBuilder builder) throws Exception {
        // git remote add <shortname> <url>命令真实的用途是：
        // 将远程仓库唯一的URL 映射成为在本地仓库中对远程仓库起的别名<shortname>，
        // 来帮助Git使用者简易编写涉及远程仓库的命令。
        // 如果不主动指定别名，默认别名就是 origin
        String cmd = "git remote add $shortname $url";
        cmd= cmd.replace("$shortname" ,"newLocalRepoShortName");
        cmd= cmd.replace("$url" ,"https://gitee.com/hnyer/GitDemo1.git");
        builder.command(cmd.split(" ")).start().waitFor();

        //builder.command("git remote remove remote".split(" ")).start().waitFor();
        LyLog.showLog("\n远程仓库信息：");
        builder.command("git remote -v".split(" ")).start().waitFor();

    }

    public static void checkGitBaseInfo(ProcessBuilder builder) throws Exception {
        LyLog.showLog("\n远程仓库信息：");
        builder.command("git", "remote", "-v").start().waitFor();

        LyLog.showLog("\n远程分支：");
        builder.command("git", "branch", "-r").start().waitFor();

        LyLog.showLog("\n本地分支：");
        builder.command("git", "branch").start().waitFor();

        LyLog.showLog("\n当前状态-------------->");
        builder.command("git status".split(" ")).start().waitFor();
    }

    public static void pullCmd(ProcessBuilder builder) throws Exception {
        LyLog.showLog("开始pull代码...");
        String currentDir = System.getProperty("user.dir");
        LyLog.showLog("当前目录="+currentDir);
        builder.command("git pull".split(" ")).start().waitFor();

        File workFile = new File(builder.directory().getCanonicalPath());
        File parentFile = workFile.getParentFile();
        File[] files = parentFile.listFiles();
        if (files == null) {
            return;
        }

        for (File file : files) {
            builder.directory(new File(file.getCanonicalPath()));
            LyLog.showLog("sub当前目录="+builder.directory().getCanonicalPath());
            builder.command("git pull".split(" ")).start().waitFor();
        }
        builder.directory(new File(currentDir));
    }

    /**
     * 推送之前要 add 和commit，
     * 用这种脚本不方便，还不如直接用 Androidstudio的 git 插件
     */
    public static void pushCode(ProcessBuilder builder) throws Exception {
        LyLog.showLog("\n开始push代码...");
        builder.command("git add ./".split(" ")).start().waitFor();

        // git push origin develop:develop
        // git push 远程仓库名 本地分支名:远程仓库名
        String cmd = "git push origin master:master";
        String[] cmds = cmd.split(" ");
        builder.command(cmds).start().waitFor();
    }

    public static void clonePro(ProcessBuilder builder) throws Exception {
        File workFile = new File(builder.directory().getCanonicalPath());
        File parentFile = workFile.getParentFile();
        LyLog.showLog("parentFile==" + parentFile.getParentFile());

        HashMap<String, String> map = new HashMap<>();
        map.put("https://gitee.com/hnyer/GitDemo2.git", parentFile.getCanonicalPath() + "\\GitDemo2\\");
        map.put("https://gitee.com/hnyer/GitDemo3.git", parentFile.getCanonicalPath() + "\\GitDemo3\\");

        for (String key : map.keySet()) {
            String value = map.get(key);

            File proDir = new File(value);
            deleteFolder(proDir);

            // git clone <remote-url> , 可以使用URL，也可以使用别名
            LyLog.showLog("\n开始 clone 代码...");
            String cmd = "git clone " + key + " " + value;
            String[] cmds = cmd.split(" ");
            int exitCode = builder.command(cmds).start().waitFor();
            System.out.println("---------" + exitCode + " (0代表成功)----------\n");
        }
    }


    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteFolder(file);
                } else {
                    //LyLog.showLog("删除文件="+file.getName());
                    file.delete();
                }
            }
        }
        folder.delete();
    }
}
